package io.bluerain.aclient.attach;

import io.bluerain.core.Http;

import javax.ws.rs.core.Form;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created by wscl on 2015/6/14.
 */
public class IndieParam {
    private Map<String, Object> ps = null;
    private Object entity;

    /**
     * 创建一个IndieQueryParam对象
     *
     * @return this
     */
    public static IndieParam builder() {
        IndieParam iqp = new IndieParam();
        iqp.ps = new LinkedHashMap<>();
        return iqp;
    }

    public static IndieParam builder(Object entity) {
        IndieParam iqp = new IndieParam();
        iqp.ps = new LinkedHashMap<>();
        iqp.entity = entity;
        return iqp;
    }

    public IndieParam put(String key, Object value) {
        this.ps.put(key, value);
        return this;
    }

    public IndieParam put(String kvMergeStr) {
        if (kvMergeStr == null) {
            System.out.println("POST参数键值对为空。");
        }
        String regex = ":";
        String key = "";
        String value = "";
        String[] kv = kvMergeStr.split(regex);
        if (kv.length > 0)
            key = kv[0];
        if (kv.length > 1)
            value = kv[1];
        this.ps.put(key, value);
        return this;
    }

    public IndieParam parse(Map<String, Object> map) {
        for (Map.Entry<String, Object> m : map.entrySet())
            put(m.getKey(), m.getValue().toString());
        return this;
    }

    @Override
    public String toString() {
        return Http.buildGetParamsStr(ps);
    }

    public Map<String, Object> toMap() {
        return this.ps;
    }

    public Form toForm() {
        Form form = new Form();
        for (Map.Entry<String, Object> param : ps.entrySet()) {
            form.param(param.getKey(), param.getValue().toString());
        }
        return form;
    }

    public Object getEntity() {
        return entity;
    }
}
